//
//  HJConversationController.m
//  KaiChat
//
//  Created by lx on 2023/10/16.
//

#import "HJConversationController.h"
#import "QMUIButton.h"
#import "HJMineController.h"
#import "HJMinePresent.h"
#import "HJVersionUpdate.h"
#import "HJWebSocketManager.h"
#import "HJIM.h"
#import "HJConversationCell.h"
#import "HJChatController.h"
#import "HJAlertController.h"
#import "HJPopMenuController.h"
#import "QMUITextField.h"
#import "HJAddFriendController.h"
#import "HJNavigationController.h"
#import "HJSelectFridendsController.h"
#import "HJUIAlertController.h"
#import "HJNetworkErrorView.h"
#import "TJEmptyDataHandler.h"
#import "HJSearchView.h"
#import "HJChatGroupModel.h"
#import "HJUnReadView.h"
#import "HJSupportController.h"
#import "HJUserNotifications.h"
#import "AppDelegate.h"
#import "HJGroupMemberModel.h"
#import "HJSwiftJsonAnimationView.h"
#import "KaiChat-Swift.h"
#import "HJFlutterController.h"
#import "HJScanController.h"

#import <UserNotifications/UserNotifications.h>
#import <Intents/Intents.h>

@interface HJConversationController ()<QMUITextFieldDelegate, HJConversationCellDelegate>

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableDictionary *originalDict;
@property (nonatomic, copy) NSString *keyword;
@property (nonatomic, weak) HJPopMenuController *popMenuController;
@property (nonatomic, weak) HJNetworkErrorView *networkErrorView;
@property (nonatomic, weak) UIView *headerView;
@property (nonatomic, weak) UIView *searchView;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, weak) UITextField *textField;
@property (nonatomic, weak) HJSwiftJsonAnimationView *lottieAnimationView;
@property (nonatomic, weak) UIView *integralView;
@property (nonatomic, assign) BOOL isWaitingReceiveIntegral;

@end

@implementation HJConversationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.lineView.hidden = YES;
    self.datas = [NSMutableArray array];
    self.originalDict = [NSMutableDictionary dictionary];
    
    UIImageView *logoImageView = [UIImageView addToView:self.navigationBar.contentView];
    logoImageView.image = [UIImage imageNamed:@"bigLogo"];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.centerY.offset(0);
    }];
    
    HJBarButton *moreButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"more_icon"] target:self action:@selector(didClickMoreButton:)];
    [self.navigationBar.contentView addSubview:moreButton];
    [moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(32);
        make.centerY.offset(0);
        make.right.inset(15);
    }];
    
    HJBarButton *scanButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"scan_icon"] target:self action:@selector(didClickScanButton)];
    [self.navigationBar.contentView addSubview:scanButton];
    [scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(32);
        make.centerY.offset(0);
        make.right.equalTo(moreButton.mas_left).inset(4);
    }];
    
    UIView *integralView = [UIView addToView:self.navigationBar.contentView];
    [integralView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(44);
        make.centerY.offset(0);
        make.right.equalTo(scanButton.mas_left).inset(2);
    }];
    
    HJBarButton *integralButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"integral_icon"] target:self action:@selector(didClickIntegralButton)];
    [integralView addSubview:integralButton];
    [integralButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(32);
        make.center.offset(0);
    }];
    
    _integralView = integralView;

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 45)];
    headerView.backgroundColor = UIColor.whiteColor;
    
    HJNetworkErrorView *networkErrorView = [HJNetworkErrorView addToView:headerView];
    networkErrorView.hidden = YES;
    [networkErrorView addTapGesturesWithTarget:self action:@selector(tapNetworkErrorView)];
    [networkErrorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(0);
        make.top.offset(0);
    }];
    
    HJSearchView *searchView = [HJSearchView addToView:headerView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(5);
        make.height.offset(36);
    }];
    
    QMUITextField *textField = searchView.textField;
    textField.placeholder = @"Search";
    textField.maximumTextLength = 30;
    textField.returnKeyType = UIReturnKeySearch;
    textField.delegate = self;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.tableHeaderView = headerView;
    self.view.backgroundColor = UIColor.tj_backgroundColor;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerClass:HJConversationCell.class forCellReuseIdentifier:@"HJConversationCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 70;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.offset(0);
        make.bottom.inset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
        dataModel.text = @"No messages";
        dataModel.iconName = @"no_message_icon";
        return TJEmptyDataTypeBase;
    }];
    
    _networkErrorView = networkErrorView;
    _searchView = searchView;
    _headerView = headerView;
    
    [self registeredNotification];
    [self loadData];
    [self requestNotificationAuthorization];
}

- (void)didClickIntegralButton {
    HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageIntegral];
    [self.navigationController pushViewController:flutterController];
}

- (void)requestNotificationAuthorization {
    
    //    [HJUserNotifications requestAuthorizationWithOptionsCompletionHandler:^(BOOL granted, NSError * _Nullable error) {
    //        if (granted) {
    //            NSLog(@"已授权");
    //        } else {
    //            NSLog(@"未获取到授权 error = %@", error);
    //        }
    //    }];
}

- (void)loadData {
    [self loadConversationDataCompletion:nil];
}

- (void)tapNetworkErrorView {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
}

- (void)registeredNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateConversationInfoNotification:) name:updateConversationInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateOrAddConversationNotification:) name:updateConversationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWebSocketConnectStateChangeNotification:) name:webSocketConnectStateChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkingReachabilityDidChangeNotification:) name:networkingReachabilityDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeleteConversationNotification:) name:deleteConversationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOfflineMessageLoadCompleteNotification:) name:offlineMessageLoadCompleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshGroupInfoNotification:) name:refreshGroupInfoNotification object:nil];
}


- (void)handleRefreshGroupInfoNotification:(NSNotification *)not {
 
    id object = not.object;
    
    if ([object isKindOfClass:HJChatGroupModel.class]) {
        
        HJChatGroupModel *groupModel = (HJChatGroupModel *)object;
        HJChatSessionModel *sessionModel = [self getSessionModelWithSessionId:groupModel.groupId];
        if (!sessionModel) return;
        
        BOOL isUpdate = !(groupModel.avatar && [groupModel.avatar isEqualToString:sessionModel.sessionAvatar] && [groupModel.name isEqualToString:sessionModel.sessionName]);
        if (isUpdate) {
            sessionModel.sessionAvatar = groupModel.avatar;
            sessionModel.sessionName = groupModel.name;
            [sessionModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {}];
            
            dispatch_async_main_queue(^{
                [self.originalDict setValue:sessionModel forKey:sessionModel.sessionId];
                for (HJConversationCell *cell in self.tableView.visibleCells) {
                    if ([cell.model.sessionId isEqualToString:groupModel.groupId]) {
                        cell.model = sessionModel;
                        break;
                    }
                };
            });
        }
    }
}

- (void)handleOfflineMessageLoadCompleteNotification:(NSNotification *)not {
    
    NSArray *sessionModels = not.object;
    if (sessionModels.count) {
        NSMutableDictionary *Mdict = [NSMutableDictionary dictionary];
        for (HJChatSessionModel *model in self.datas) {
            [Mdict setObject:model forKey:model.sessionId];
        }
        for (HJChatSessionModel *model in sessionModels) {
            [Mdict setObject:model forKey:model.sessionId];
        }
        [self resetDataWithConversationModels:Mdict.allValues];
    } else {
        dispatch_async_main_queue(^{
            if (self.datas.count == 0) {//显示空数据占位图
                [self.tableView reloadData];
            }
        });
    }
}

- (void)handleDeleteConversationNotification:(NSNotification *)not {
    
    TJLog(@"%s", __func__);
    
    NSString *sessionId = not.object;
    
    HJChatSessionModel *targetMdoel = [self getSessionModelWithSessionId:sessionId];
    
    if (targetMdoel) {
        [self.datas removeObject:targetMdoel];
        [self.originalDict removeObjectForKey:targetMdoel.sessionId];
        [self.tableView reloadData];
    }
}

- (void)handleNetworkingReachabilityDidChangeNotification:(NSNotification *)not {
    AFNetworkReachabilityStatus status = [not.object integerValue];
    
    if ((status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)) {
        
        self.networkErrorView.hidden = YES;
        self.headerView.tj_height = 45;
        self.tableView.tableHeaderView = self.headerView;
        
        [self.networkErrorView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(leftRightMargin);
            make.height.offset(0);
            make.top.offset(0);
        }];
        
        [self.searchView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(leftRightMargin);
            make.top.offset(5);
            make.height.offset(36);
        }];
        
    } else {
        
        self.networkErrorView.hidden = NO;
        self.headerView.tj_height = 86;
        self.tableView.tableHeaderView = self.headerView;
        
        [self.networkErrorView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(leftRightMargin);
            make.height.offset(36);
            make.top.offset(5);
        }];
        
        [self.searchView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(leftRightMargin);
            make.top.equalTo(self.networkErrorView.mas_bottom).offset(5);
            make.height.offset(36);
        }];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSLog(@"%s", __func__);
    self.emptyDataHandler.canDisplay = NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"%s", __func__);
    self.emptyDataHandler.canDisplay = YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    _keyword = textField.text;
    
    if (isEmptyString(_keyword)) {
        
        if (self.originalDict.count == 0) {
            [self loadConversationDataCompletion:^{}];
            return;
        }
        
        for (HJChatSessionModel *obj in self.originalDict.allValues) {
            obj.sessionNameAttributedstring = nil;
        }
        [self.datas removeAllObjects];
        [self.datas addObjectsFromArray:self.originalDict.allValues];
        [self sortedDatas];
        [self.tableView reloadData];
        [self reloadUnReadCount];
        return;
    }
    
    [self.datas removeAllObjects];
    for (HJChatSessionModel *obj in self.originalDict.allValues) {
        NSRange range = [obj.sessionName rangeOfString:self.keyword options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.sessionName];
            [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
            obj.sessionNameAttributedstring = attrStr;
            [self.datas addObject:obj];
        } else {
            obj.sessionNameAttributedstring = nil;
        }
    }
    
    [self sortedDatas];
    [self.tableView reloadData];
    [self reloadUnReadCount];
}

- (void)didClickMoreButton:(HJBarButton *)button {
    
    button.selected = YES;
    
    [UIView animateWithDuration:0.2 animations:^{
        button.transform = CGAffineTransformRotate(button.transform, M_PI_4);;
    }];
    
    HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:@[
        @(HJPopMenuTypeAddFriend),
        @(HJPopMenuTypeCreateGroup),
    ]];
    
    TJWeakify(self)
    popMenuController.controllerName = NSStringFromClass(self.class);
    [popMenuController showInController:self];
    [popMenuController setDismissBlock:^{
        button.selected = NO;
        [UIView animateWithDuration:0.25 animations:^{
            button.transform = CGAffineTransformIdentity;
        }];
    }];
    [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
        
        if (type == HJPopMenuTypeAddFriend) {
            HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:[[HJAddFriendController alloc] init]];
            [weakself presentViewController:navController animated:YES completion:nil];
            return;
        }
        
        if (type == HJPopMenuTypeCreateGroup) {
            HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:[[HJSelectFridendsController alloc] init]];
            [weakself presentViewController:navController animated:YES completion:nil];
            return;
        }
    }];
}


- (void)tapPersonalCenterView {
    
}


- (void)didClickFriendButton {
    [self.navigationController pushViewControllerWithName:@"HJFriendListController"];
}


- (void)handleUpdateConversationInfoNotification:(NSNotification *)not {
    [self handleUpdateConversationInfo:not.object];
}

- (void)handleWebSocketConnectStateChangeNotification:(NSNotification *)not {
    HJWebSocketConnectState state = [not.object integerValue];
    if (state == HJWebSocketConnectStateConnecting) {
        
    } else if (state == HJWebSocketConnectStateSucceed) {
        
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.tableView.tableHeaderView.superview bringSubviewToFront:self.tableView.tableHeaderView];
}

- (void)reloadUnReadCount {
    NSInteger totalCount = 0;
    for (HJChatSessionModel *sessionModel in self.datas) {
        if (!sessionModel.isMute.boolValue) {
            totalCount += sessionModel.unReadCount.integerValue;
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:messageBadgeChangeNotification object:@(totalCount)];
}

- (void)sortedDatas {
    NSMutableArray *topArray = [NSMutableArray array];
    NSMutableArray *messageArray = [NSMutableArray array];
    
    for (HJChatSessionModel *model in self.datas) {
        [self.originalDict setValue:model forKey:model.sessionId];
        if (model.isTop.boolValue) {
            [topArray addObject:model];
        } else {
            [messageArray addObject:model];
        }
    }
    
    [self.datas removeAllObjects];
    
    if (topArray.count) {
        NSArray *sortedArray = [topArray sortedArrayUsingComparator:^NSComparisonResult(HJChatSessionModel *obj1, HJChatSessionModel *obj2) {
            NSString *objec1SortTimestamp = obj1.topTimestamp.integerValue > obj1.timestamp.integerValue ? obj1.topTimestamp : obj1.timestamp;
            NSString *objec2SortTimestamp = obj2.topTimestamp.integerValue > obj2.timestamp.integerValue ? obj2.topTimestamp : obj2.timestamp;
            return [objec2SortTimestamp compare:objec1SortTimestamp];
        }];
        [self.datas addObjectsFromArray:sortedArray];
    }
    
    
    if (messageArray) {
        NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
        [messageArray sortUsingDescriptors:@[sortDescriptor]];
        [self.datas addObjectsFromArray:messageArray];
    }
    
}

- (nullable HJChatSessionModel *)getSessionModelWithSessionId:(NSString *)sessionId {
    HJChatSessionModel *targetMdoel = nil;
    for (HJChatSessionModel *sessionModel in self.datas) {
        if ([sessionModel.sessionId isEqualToString:sessionId]) {
            targetMdoel = sessionModel;
            break;
        }
    }
    return targetMdoel;
}

- (void)handleUpdateOrAddConversationNotification:(NSNotification *)not {
    
    HJChatSessionModel *obj = not.object;
    if (!obj) {
        [self loadConversationDataCompletion:nil];
        return;
    }
    
    dispatch_async_main_queue(^{
        
        HJChatSessionModel *targetMdoel = [self getSessionModelWithSessionId:obj.sessionId];
        if (targetMdoel) {
            if (!obj.isTop) {
                obj.isTop = targetMdoel.isTop;
            }
            if (!obj.isMute) {
                obj.isMute = targetMdoel.isMute;
            }
            
            if (!obj.sessionName) {
                obj.sessionName = targetMdoel.sessionName;
            }
            
            if (!obj.sessionAvatar) {
                obj.sessionAvatar = targetMdoel.sessionAvatar;
            }
            
            NSInteger index = [self.datas indexOfObject:targetMdoel];
            [self.datas replaceObjectAtIndex:index withObject:obj];
        } else {
            [self.datas addObject:obj];
        }
        [self.originalDict setValue:obj forKey:obj.sessionId];
        [self sortedDatas];
        [self reloadUnReadCount];
        [self.tableView reloadData];
    });
}

- (void)handleUpdateConversationInfo:(HJChatSessionModel *)sessionModel {
    if (!sessionModel) return;
    
    dispatch_async_main_queue(^{
        
        HJChatSessionModel *targetMdoel = [self getSessionModelWithSessionId:sessionModel.sessionId];

        if (!targetMdoel) return;
        
        if (sessionModel.isTop) {
            targetMdoel.isTop = sessionModel.isTop;
        }
        
        if (sessionModel.isMute) {
            targetMdoel.isMute = sessionModel.isMute;
        }
        
        if (sessionModel.hasNotice) {
            targetMdoel.hasNotice = sessionModel.hasNotice;
        }
        
        if (sessionModel.unReadCount) {
            targetMdoel.unReadCount = sessionModel.unReadCount;
        }
        
        if (sessionModel.readMessageTimestamp) {
            targetMdoel.readMessageTimestamp = sessionModel.readMessageTimestamp;
        }
        
        if (sessionModel.sessionName) {
            targetMdoel.sessionName = sessionModel.sessionName;
        }
        
        if (sessionModel.sessionAvatar) {
            targetMdoel.sessionAvatar = sessionModel.sessionAvatar;
        }
        
        if (sessionModel.isTop) {
            [self sortedDatas];
            [self.tableView reloadData];
        } else {
            [self.originalDict setValue:targetMdoel forKey:targetMdoel.sessionId];
            for (HJConversationCell *cell in self.tableView.visibleCells) {
                if ([cell.model.sessionId isEqualToString:targetMdoel.sessionId]) {
                    cell.model = targetMdoel;
                    break;
                }
            }
        }
        
        if (sessionModel.isMute) {
            [self reloadUnReadCount];
        }
    });
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.textField.enabled = self.datas.count > 0;
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJChatSessionModel *model = self.datas[indexPath.row];
    HJConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJConversationCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_popMenuController) {
        return;
    }
    
    HJConversationCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.model.officialType == HJChatOfficialTypeKaiNews) {
        [self.navigationController pushViewControllerWithName:@"HJNewsController"];
        return;
    }
    
    if (cell.model.officialType == HJChatOfficialTypeKaiSupport) {
        HJSupportController *supportController = [[HJSupportController alloc] init];
        supportController.sessionModel = cell.model;
        [self.navigationController pushViewController:supportController];
        return;
    }
    
    if (cell.model.officialType == HJChatOfficialTypeKaiPay) {
        [self.navigationController pushViewControllerWithName:@"HJPayBillController"];
        return;
    }
    
    HJChatController *chatController = [HJChatController chatControllerWithSessionModel:cell.model];
    [self.navigationController pushViewController:chatController];
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJWeakify(self)
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:nil handler:^(UIContextualAction * _Nonnull action, UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [weakself deleteConversationWithIndexPath:indexPath];
        completionHandler(YES);
    }];
    
    deleteAction.backgroundColor = UIColor.tj_FFEEE6Color;
    deleteAction.image = [UIImage imageNamed:@"cell_delete"];
    
    UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    return configuration;
}

- (void)tableViewCellLongPressGesture:(HJConversationCell *)cell {
    HJChatSessionModel *model = cell.model;
    NSMutableArray *types = [NSMutableArray array];
    [types addObject: @(model.isTop.boolValue ? HJPopMenuTypeCancelTop : HJPopMenuTypeTop)];
    if (![cell.model.sessionId isEqualToString:HJUserInfo.userId]) {
        [types addObject:@(model.isMute.boolValue ? HJPopMenuTypeUnmute : HJPopMenuTypeMute)];
    }
    [types addObject:@(HJPopMenuTypeDelete)];
    
    HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:types];
    _popMenuController = popMenuController;
    TJWeakify(self)
    popMenuController.sourceRect = [cell.superview convertRect:cell.frame toView:self.view];
    [popMenuController showInController:self];
    
    [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
        
        if (type == HJPopMenuTypeTop || type == HJPopMenuTypeCancelTop) {
            BOOL isTop = HJPopMenuTypeTop == type;
            [HJIM.shareIM.conversationManager topWithSessionId:model.sessionId isTop:isTop type:model.chatType complete:^(NSError * _Nonnull error) {
                if (error) return;
                model.isTop = toString(@(isTop));
                if (isTop) {
                    model.topTimestamp = [NSString stringWithFormat:@"%.f", [NSDate date].timeIntervalSince1970 * 1000];
                } else {
                    model.topTimestamp = @"";
                }
                [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                    [weakself sortedDatas];
                    dispatch_async_main_queue(^{
                        [weakself.tableView reloadData];
                    });
                }];
                
            }];
            return;
        }
        
        if (type == HJPopMenuTypeMute || type == HJPopMenuTypeUnmute) {
            BOOL isMute = type == HJPopMenuTypeMute;
            [HJIM.shareIM.conversationManager muteWithSessionId:model.sessionId isMute:isMute type:model.chatType complete:^(NSError * _Nonnull error) {
                if (error) return;
                
                model.isMute = toString(@(isMute));
                [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                    dispatch_async_main_queue(^{
                        cell.model = model;
                        [weakself reloadUnReadCount];
                    });
                }];
            }];
            return;
        }
        
        if (type == HJPopMenuTypeDelete) {
            [weakself deleteConversationWithIndexPath:[weakself.tableView indexPathForCell:cell]];
            return;
        }
        
    }];
    
}

- (void)deleteConversationWithIndexPath:(NSIndexPath *)indexPath {
    
    HJChatSessionModel *model = self.datas[indexPath.row];
    
    HJUIAlertController *alert = [HJUIAlertController alertControllerWithTitle:nil message:@"This user's information on this device will be cleared" preferredStyle:HJUIAlertControllerStyleActionSheet];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Delete" style:HJUIAlertActionStyleDestructive handler:^(HJUIAlertAction * _Nonnull action) {
        [HJIM.shareIM.conversationManager deleteConversationWithSessionId:model.sessionId completion:^(NSError * _Nonnull error) {
            [self.datas removeObject:model];
            [self.originalDict removeObjectForKey:model.sessionId];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
            if (self.datas.count == 0) {
                [self.tableView reloadData];
            }
        }];
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Cancel" style:HJUIAlertActionStyleCancel handler:^(HJUIAlertAction * _Nonnull action) {
        
    }]];
    
    [alert showInViewController:self];
}

- (void)resetDataWithConversationModels:(NSArray *)models {
    
    [self.originalDict removeAllObjects];
    [self.datas removeAllObjects];
    
    if (models.count) {
        [self.datas addObjectsFromArray:models];
    }
    
    [self sortedDatas];
    
    dispatch_async_main_queue(^{
        self.emptyDataHandler.canDisplay = YES;
        [self reloadUnReadCount];
        [self.tableView reloadData];
    });
}

- (void)loadConversationDataCompletion:(void (^__nullable)(void))completion {
    [[HJIM shareIM].conversationManager allConversationListCompletion:^(NSArray * _Nonnull list) {
        [self resetDataWithConversationModels:list];
        if (completion) {
            completion();
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [HJWebSocketManager.shareManager tryConnect];
    [HJMinePresent integraWaitingReceiveComplete:^(BOOL isReceive) {
      
        if (isReceive == self.isWaitingReceiveIntegral) return;
        [self setIsWaitingReceiveIntegral:isReceive];
    }];
}

- (void)setIsWaitingReceiveIntegral:(BOOL)isWaitingReceiveIntegral {
    _isWaitingReceiveIntegral = isWaitingReceiveIntegral;
    
    [self.integralView removeAllSubview];
    if (self.lottieAnimationView) {
        [self.lottieAnimationView stop];
    }
    
    if (isWaitingReceiveIntegral) {
        
        HJSwiftJsonAnimationView *lottieAnimationView = [[HJSwiftJsonAnimationView alloc] initWithName:@"gift"];
        lottieAnimationView.isLoop = YES;
        [self.integralView addSubview:lottieAnimationView];
        [lottieAnimationView addTapGesturesWithTarget:self action:@selector(didClickIntegralButton)];
        [lottieAnimationView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(32);
            make.centerX.offset(0);
            make.centerY.offset(-6);
        }];
        self.lottieAnimationView = lottieAnimationView;
        [lottieAnimationView playComplete:^(BOOL res) {}];
    } else {
        HJBarButton *integralButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"integral_icon"] target:self action:@selector(didClickIntegralButton)];
        [self.integralView addSubview:integralButton];
        [integralButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(32);
            make.center.offset(0);
        }];
    }
    
}

- (void)didClickScanButton {
    HJScanController *scanController = [[HJScanController alloc] init];
    [scanController showInController:self];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
